package com.example.netty.client.tcp;

import com.example.netty.service.NettyClient;
import com.example.netty.model.CallBack;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.util.AttributeKey;
import io.netty.util.CharsetUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.TimeUnit;

public class TcpClient implements NettyClient {


    private final static Logger logger = LoggerFactory.getLogger(TcpClient.class);

    /**
     * 设置通用key
     */
    public static final AttributeKey<CallBack> callBackAttributeKey = AttributeKey.valueOf("callBackAttributeKey");

    private static final EventLoopGroup group = new NioEventLoopGroup();

    private static final TcpClientHandler tcpClientHandler = new TcpClientHandler();

    private Channel clientChannel = null;

    private final String ip;

    private final int port;

    public TcpClient(String ip, int port) {
        this.ip = ip;
        this.port = port;
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(group)
                .channel(NioSocketChannel.class)
                .option(ChannelOption.TCP_NODELAY, true)
                .option(ChannelOption.SO_KEEPALIVE, true)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        socketChannel.pipeline().addLast("decoder", new StringDecoder(CharsetUtil.UTF_8));
                        socketChannel.pipeline().addLast("encoder", new StringEncoder(CharsetUtil.UTF_8));
                        socketChannel.pipeline().addLast(tcpClientHandler);
                    }
                });
        ChannelFuture channelFuture = bootstrap.connect(ip, port);
        try {
            this.clientChannel = channelFuture.sync().channel();
            //注册连接事件监听器
            channelFuture.addListener((ChannelFutureListener) future -> {
                if (future.isSuccess()) {
                    logger.debug("服务端{}:{}连接成功，ID:{}", ip, port, clientChannel.id());
                } else {
                    logger.debug("服务端{}:{}连接失败，ID:{}", ip, port, clientChannel.id());
                }
            });
            //注册关闭事件监听器
            clientChannel.closeFuture().addListener(cfl -> {
                logger.debug("服务端{}:{}断开连接，ID:{}", ip, port, clientChannel.id());
            });

        } catch (Exception e) {
            logger.warn("", e);
        }
    }


    /**
     * 关闭连接
     */
    @Override
    public void close() {
        try {
            if (clientChannel != null) {
                clientChannel.close().sync();
            }
        } catch (Exception e) {
            logger.error("", e);
        }
    }


    /**
     * 判断连接是否可用
     *
     * @return
     */
    public boolean isOpen() {
        try {
            return clientChannel.isOpen();
        } catch (Exception e) {
            logger.error("", e);
            return false;
        }
    }


    /**
     * 发送消息并同步等待数据返回
     *
     * @param msg
     * @param timeOutMilliseconds
     * @return
     */
    public synchronized String send(String msg, long timeOutMilliseconds) throws Exception {
        if (clientChannel == null) {
            TcpClientCache.removeClient(ip, port);
            throw new Exception(ip + "已断开连接...");
        }
        CallBack callBack = new CallBack(1);
        clientChannel.attr(callBackAttributeKey).set(callBack);
        clientChannel.writeAndFlush(msg);
        callBack.await(timeOutMilliseconds, TimeUnit.MILLISECONDS);
        return callBack.getResponse();
    }
}
